package com.netty.time;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Package Name:com.my.time
 * Description: That's the purpose of the file
 * Date:2016/8/24 14:57
 * Copyright (c) 2016, zhongmu@suneee.com All Rights Reserved.
 */
public class TimeClient {

    public void connect(int port,String host) throws Exception {

        //配置客户端线程组
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //初始化脚本配置
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TimeClientHandler());
                        }
                    });
            //建立异步连接
            ChannelFuture f = b.connect(host,port).sync();

            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        System.out.println("客户端开始...");
        try {
            if(args!=null && args.length>0){
                port = Integer.valueOf(args[0]);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        new TimeClient().connect(port,"127.0.0.1");
    }
}
